package com.stars.empoly.activity

import android.Manifest
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.utils.DistanceUtil
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.eazypermissions.common.model.PermissionResult
import com.eazypermissions.coroutinespermission.PermissionManager
import com.google.gson.Gson
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.qmuiteam.qmui.kotlin.onClick
import com.qmuiteam.qmui.widget.QMUIRadiusImageView
import com.stars.empoly.R
import com.stars.empoly.adapter.ReceivedAdapter
import com.stars.empoly.adapter.ServerListAdapter
import com.stars.empoly.base.MBActivity
import com.stars.empoly.config.ConfigRx
import com.stars.empoly.databinding.ActivityReceivedDetailsBinding
import com.stars.empoly.inte.ChoiceData
import com.stars.empoly.model.UseOrderDetail
import com.stars.empoly.utils.DecimalUtils
import com.stars.empoly.utils.PopuCancelUtils
import com.stars.empoly.utils.PopuPayUtils
import com.stars.empoly.utils.PopuToCancelUtils
import com.stars.empoly.vmodel.ReceivedDetailsVModel
import com.trailer.base.utils.B
import com.trailer.base.utils.DialUtils
import com.trailer.base.utils.UiSwitch
import kotlinx.coroutines.launch

/**
 *on 2022/9/24
 */
class ReceivedDetailsActivity :
    MBActivity<ReceivedDetailsVModel, ActivityReceivedDetailsBinding>() {

    // 地图View实例
    private var mMapView: MapView? = null
    private var mBaiduMap: BaiduMap? = null
    private var mBitmapDescriptorStart: BitmapDescriptor? = null

    var latEnd: LatLng? = null
    private var mMarker: Marker? = null


    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        vm.id = intent?.extras?.getString("id")
        vm.getInfo()

        vm.bean.observe(this) {
            if(it.status==-2||it.status==-1||it.status==0||it.status==3||(it.status==1&&it.technicianStatus==0)||
                it.technicianStatus==5){
                //未接单的详情
                binding.llReceive.visibility=View.VISIBLE
                binding.llOrder.visibility=View.GONE
                //评分
                if (it.isComment == 1 && it.technicianStatus == 5) {
                    when (it.stars) {
                        1 -> {
                            binding.startOne.setImageResource(R.drawable.me_start_on)
                        }
                        2 -> {
                            binding.startOne.setImageResource(R.drawable.me_start_on)
                            binding.startTwo.setImageResource(R.drawable.me_start_on)

                        }
                        3 -> {
                            binding.startOne.setImageResource(R.drawable.me_start_on)
                            binding.startTwo.setImageResource(R.drawable.me_start_on)
                            binding.startThree.setImageResource(R.drawable.me_start_on)

                        }
                        4 -> {
                            binding.startOne.setImageResource(R.drawable.me_start_on)
                            binding.startTwo.setImageResource(R.drawable.me_start_on)
                            binding.startThree.setImageResource(R.drawable.me_start_on)
                            binding.startFour.setImageResource(R.drawable.me_start_on)
                        }
                        5 -> {
                            binding.startOne.setImageResource(R.drawable.me_start_on)
                            binding.startTwo.setImageResource(R.drawable.me_start_on)
                            binding.startThree.setImageResource(R.drawable.me_start_on)
                            binding.startFour.setImageResource(R.drawable.me_start_on)
                            binding.startFive.setImageResource(R.drawable.me_start_on)


                        }
                    }
                }
                //设置匿名
                vm.anonymous.value = it.isAnonymous != 0

                //订单跟踪
                if (null != it.technicianRecord) {

                    var adapter = ReceivedAdapter()
                    binding.recyclerRecord.adapter = adapter
                    adapter.addData(it.technicianRecord)
                }

                if (null != it.serviceInfo) {
                    var adapter = ServerListAdapter()
                    binding.recyclerView.adapter = adapter
                    adapter.addData(it.serviceInfo)

                    var time: Int = 0
                    for (item in it.serviceInfo) {
                        if (null != item.time && item.time != "") {
                            time += item.time.toInt()
                        }
                    }
                    binding.tvZTime.text = "" + time + "分钟"

                }

                //算出总距离
                try {


                    var latStart: LatLng? = null
                    if (null == it.technicianStatus) {
                        latStart =
                            LatLng(
                                it.technicianStartLatitude.toDouble(),
                                it.technicianStartLongitude.toDouble()
                            )
                    } else {
                        latStart =
                            LatLng(it.technicianLatitude.toDouble(), it.technicianLongitude.toDouble())
                    }

                    var latEnd = LatLng(it.latitude.toDouble(), it.longitude.toDouble())

                    var s1 = DistanceUtil.getDistance(latStart, latEnd) / 1000

                    var z_distance = DecimalUtils.getNumber(s1).toDouble()

                    binding.tvDistance.text = "全程" + z_distance + "km)"
                } catch (e: Exception) {

                }
            }else{
                //已接单的详情
                binding.llReceive.visibility=View.GONE
                binding.llOrder.visibility=View.VISIBLE

                initMap(it.latitude, it.longitude)
                if (it.technicianStatus == 1) {
                    binding.imgTOne.visibility = View.VISIBLE
                }
                if (it.technicianStatus == 2) {
                    binding.imgTOne.visibility = View.VISIBLE
                    binding.imgTTwo.visibility = View.VISIBLE
                }
                if (it.technicianStatus == 3) {
                    binding.imgTOne.visibility = View.VISIBLE
                    binding.imgTTwo.visibility = View.VISIBLE
                    binding.imgTThree.visibility = View.VISIBLE
                }
                if (it.technicianStatus == 4) {
                    binding.imgTOne.visibility = View.VISIBLE
                    binding.imgTTwo.visibility = View.VISIBLE
                    binding.imgTThree.visibility = View.VISIBLE
                    binding.imgTFour.visibility = View.VISIBLE
                }

                updateMarker(it)
                var latStart: LatLng? = null
                //算出总距离
                try {

                    if (null == it.technicianStatus) {
                        latStart =
                            LatLng(
                                it.technicianStartLatitude.toDouble(),
                                it.technicianStartLongitude.toDouble()
                            )
                    } else {
                        latStart =
                            LatLng(it.technicianLatitude.toDouble(), it.technicianLongitude.toDouble())
                    }

                    latEnd = LatLng(it.latitude.toDouble(), it.longitude.toDouble())

                    var s1 = DistanceUtil.getDistance(latStart, latEnd) / 1000

                    var z_distance = DecimalUtils.getNumber(s1).toDouble()

                    binding.tvTDistance.text = "距离你" + z_distance + "km"

                    //去开启连续定位
                    //获取一次定位todo:
                    handler.sendEmptyMessageDelayed(0x101, 1000)
                } catch (e: Exception) {

                }
            }





        }


    }


    private fun initMap(latitude: String, longitude: String) {
        mMapView = binding.mapview
        if (null == mMapView) {
            return
        }
        mBaiduMap = mMapView?.map
        if (null == mBaiduMap) {
            return
        }

        // 使得圆角地图情况下，地图log不会被遮盖
        mBaiduMap?.setViewPadding(30, 0, 30, 20)

        // 设置初始中心
        val start = LatLng(latitude.toDouble(), longitude.toDouble())
        val mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(start, 12f)
        mBaiduMap?.setMapStatus(mapStatusUpdate)

    }

    /**
     * 更新marker状态
     */
    private fun updateMarker(bean: UseOrderDetail) {

        //设置用户的位置  icon_binding_point  icon_start_custom
        mBitmapDescriptorStart = BitmapDescriptorFactory.fromResource(R.drawable.icon_binding_point)


        val start = LatLng(bean.technicianLatitude.toDouble(), bean.technicianLongitude.toDouble())

        var markerOptions = MarkerOptions()
            .position(start)
            .icon(mBitmapDescriptorStart)
//        mBaiduMap?.addOverlay(markerOptions)

        mMarker = mBaiduMap!!.addOverlay(markerOptions) as Marker


        val inflate: View =
            LayoutInflater.from(this@ReceivedDetailsActivity).inflate(R.layout.map_view, null)
        var img = inflate.findViewById<QMUIRadiusImageView>(R.id.img)
        if (null != bean.headImage && !TextUtils.isEmpty(bean.headImage)) {

            Glide.with(this@ReceivedDetailsActivity)
                .asBitmap()
                .load(bean.headImage)
                .into(object : SimpleTarget<Bitmap>() {
                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap>?
                    ) {
                        img.setImageBitmap(resource)
                        val end = LatLng(bean.latitude.toDouble(), bean.longitude.toDouble())
                        val markerOptions1 = MarkerOptions()
                            .position(end)
                            .icon(BitmapDescriptorFactory.fromView(inflate))
                        mBaiduMap?.addOverlay(markerOptions1)


                    }
                })


        }


    }


    override fun onResume() {
        super.onResume()
        if (null != mMapView) {
            mMapView?.onResume()
        }

    }

    override fun onPause() {
        super.onPause()
        if (null != mMapView) {
            mMapView?.onPause()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            handler.removeMessages(0x101)
//
//            if (null != mMapView) {
//                mMapView!!.onDestroy()
//                mBaiduMap?.clear()
//            }
//
//            if (null != mBitmapDescriptorStart) {
//                mBitmapDescriptorStart?.recycle()
//            }
//            if (null != locationClient) {
//                locationClient?.stop()
//                locationClient = null
//            }
            finish()
            return true
        }
        return false
    }


    override fun onDestroy() {
        super.onDestroy()

        handler.removeMessages(0x101)

        if (null != mMarker) {
            mMarker?.cancelAnimation()
        }
        if (null != mMapView) {
            mMapView!!.onDestroy()
            mBaiduMap?.clear()
        }
        if (null != mBitmapDescriptorStart) {
            mBitmapDescriptorStart?.recycle()
        }
        if (null != locationClient) {
            locationClient?.stop()
            locationClient = null
        }

    }



    override fun listeners() {
        super.listeners()

        binding.llAnonymous.onClick {
            vm.anonymous.value=!vm.anonymous.value!!
        }

        binding.llPay.onClick {

            PopuPayUtils.show(context(), vm.bean.value?.payType?.toInt(),vm.bean.value?.payMoney,binding.llPay, object : ChoiceData {
                override fun onRestuse(type: String?) {


                    vm.toPay(type)
                }

            })
        }


        binding.llCancel.onClick {
            PopuToCancelUtils.show(context(), binding.llCancel, object : ChoiceData {
                override fun onRestuse(id: String?) {

                }
            })
        }

        binding.llAgain.onClick {


            UiSwitch.bundle(context(), PlaceOrderActivity::class.java,
                B().putString("id","-2")
                    .putString("beanId", vm.id).ok())
        }
        binding.imgElavOne.onClick {
            vm.stars = 1
            binding.imgElavOne.setImageResource(R.drawable.me_start_on)
            binding.imgElavTwo.setImageResource(R.drawable.me_start_off)
            binding.imgElavThree.setImageResource(R.drawable.me_start_off)
            binding.imgElavFour.setImageResource(R.drawable.me_start_off)
            binding.imgElavFive.setImageResource(R.drawable.me_start_off)

        }
        binding.imgElavTwo.onClick {
            vm.stars = 2
            binding.imgElavOne.setImageResource(R.drawable.me_start_on)
            binding.imgElavTwo.setImageResource(R.drawable.me_start_on)
            binding.imgElavThree.setImageResource(R.drawable.me_start_off)
            binding.imgElavFour.setImageResource(R.drawable.me_start_off)
            binding.imgElavFive.setImageResource(R.drawable.me_start_off)

        }
        binding.imgElavThree.onClick {
            vm.stars = 3
            binding.imgElavOne.setImageResource(R.drawable.me_start_on)
            binding.imgElavTwo.setImageResource(R.drawable.me_start_on)
            binding.imgElavThree.setImageResource(R.drawable.me_start_on)
            binding.imgElavFour.setImageResource(R.drawable.me_start_off)
            binding.imgElavFive.setImageResource(R.drawable.me_start_off)

        }
        binding.imgElavFour.onClick {
            vm.stars = 4
            binding.imgElavOne.setImageResource(R.drawable.me_start_on)
            binding.imgElavTwo.setImageResource(R.drawable.me_start_on)
            binding.imgElavThree.setImageResource(R.drawable.me_start_on)
            binding.imgElavFour.setImageResource(R.drawable.me_start_on)
            binding.imgElavFive.setImageResource(R.drawable.me_start_off)

        }
        binding.imgElavFive.onClick {
            vm.stars = 5
            binding.imgElavOne.setImageResource(R.drawable.me_start_on)
            binding.imgElavTwo.setImageResource(R.drawable.me_start_on)
            binding.imgElavThree.setImageResource(R.drawable.me_start_on)
            binding.imgElavFour.setImageResource(R.drawable.me_start_on)
            binding.imgElavFive.setImageResource(R.drawable.me_start_on)

        }
        binding.llElavSubmit.onClick {
            if (vm.stars == 0) {
                toast("至少一星！")
                return@onClick
            }

            vm.setElavSubmit()
        }


        //-----
        binding.butCancel.onClick {
            PopuCancelUtils.show(context(), binding.butCancel, object : ChoiceData {
                override fun onRestuse(id: String?) {
                    //todo 同意取消订单
                }

            })
        }

        binding.llPhone.onClick {

            //拨打电话
            launch {
                val requestPermissions = PermissionManager.requestPermissions(
                    this@ReceivedDetailsActivity, 1000, Manifest.permission.CALL_PHONE
                )
                if (requestPermissions is PermissionResult.PermissionGranted) {
                    //拨打电话
                    vm.bean.value?.phone?.let {
                        DialUtils.dialPhone(context(), it)
                    }
                }
            }
        }




    }

    override fun vmClass(): Class<ReceivedDetailsVModel> {
        return ReceivedDetailsVModel::class.java
    }

    override fun binding(): ActivityReceivedDetailsBinding {
        return ActivityReceivedDetailsBinding.inflate(layoutInflater)
    }

    override fun title(): String? {
        return "订单详情"
    }

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            setLongLocation()
        }
    }

    //一次定位
    private var locationClient: LocationClient? = null


    fun setLongLocation() {
        locationClient = LocationClient(context())
        // 设置定位条件
        val option = LocationClientOption()

        option.setIsNeedLocationPoiList(true) //获取附近 poi

//        option.setIsNeedLocationDescribe(true); //位置语义化
        option.isOpenGps = true // 是否打开GPS

        option.setCoorType("bd09ll") // 设置返回值的坐标类型

//        option.setScanSpan(5000) // 设置定时定位的时间间隔。单位毫秒
//        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setAddrType("all")
        option.setIgnoreKillProcess(false) //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.setOnceLocation(true)

        locationClient?.locOption = option

        locationClient?.registerLocationListener(object : BDAbstractLocationListener() {
            override fun onReceiveLocation(amapLocation: BDLocation?) {
                if (null != amapLocation) {


                    try {
                        var latStart =
                            LatLng(amapLocation.latitude, amapLocation.longitude)

                        var s1 = DistanceUtil.getDistance(latStart, latEnd) / 1000

                        var distance = DecimalUtils.getNumber(s1).toDouble()

                        binding.tvTDistance.text = "距离你" + distance + "km"

                        //移动market

                        mMarker?.position = latStart
//

                    } catch (e: Exception) {

                    }


                }

                handler.sendEmptyMessageDelayed(0x101, 3000)

            }
        })
        locationClient?.locOption = option

        locationClient?.start()

    }

    override val isRxbus: Boolean
        get() = true


    @Subscribe(tags = [Tag(ConfigRx.PAY_COMPLETE)])
    fun setPayComplete(type: String) {
        toast("支付成功")
        vm.getInfo()
        RxBus.get().post(ConfigRx.PLACE_ORDER, "")

    }

    @Subscribe(tags = [Tag(ConfigRx.PAY_ERROR)])
    fun setPayError(type: String) {


        toast("支付失败")

    }
}
